package znck.spring.serviceImp.parklots;

import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.sf.json.JSONObject;
import znck.spring.service.parklots.UseSdkService;
import znck.spring.service.util.SystemService;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Collections;
import java.util.List;
import znck.bean.weixin.jssdk.JsSDK;
import java.util.Map.Entry;
import java.security.MessageDigest;


@Service
public class UseSdkServiceImp implements UseSdkService{
	
	@Autowired
	SystemService systemService;
	
	@Autowired
	ServletContext servletContext;
	
	
	@Override
	public String getTiket() {
		// TODO Auto-generated method stub
		//url 是https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
		String url = systemService.getProperty_key("jsapi_ticket") + servletContext.getAttribute("access_token") +"&type=jsapi";
		StringBuffer buffer = systemService.HttpsSend(url, "get", null);
		JSONObject jsonObj = JSONObject.fromObject(buffer.toString());
		if(jsonObj.getInt("errcode")==0) {
			return jsonObj.getString("ticket");
		}else {
			return null;
		}
	}

	@Override
	public JsSDK formatQueryParaMap() {
		JsSDK jssdk = new JsSDK();
		String appId = systemService.getProperty_key("appID");
		String timestamp = Long.toString(System.currentTimeMillis() / 1000);
		String nonceStr = UUID.randomUUID().toString();
		String ticket = this.getTiket();
		System.out.print("appId :" + appId + "; timestamp :" + timestamp + "; nonceStr:" + nonceStr );
		String url = systemService.getProperty_key("basepath") + "/getJsSdk.znck";
		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("jsapi_ticket", ticket);
		paraMap.put("noncesdstr", nonceStr);
		paraMap.put("url", url);
		// TODO Auto-generated method stub
		String signature = null;
		StringBuffer buffer = new StringBuffer();
		try {
			List<Entry<String, String>> infoIds = new ArrayList<Entry<String, String>>(paraMap.entrySet());
			Collections.sort(infoIds, new Comparator<Entry<String, String>>() {
				public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
					return (o1.getKey()).toString().compareTo(o2.getKey());
				}
			});
			StringBuffer buff = new StringBuffer();
			for (int i = 0; i < infoIds.size(); i++) {
				Map.Entry<String, String> item = infoIds.get(i);
				if (null != item.getKey() && !"".equals(item.getKey())) {
					String key = item.getKey();
					String val = item.getValue();
					buff.append(key + "=" + val + "&");
				}
			}
			signature = buff.toString();
			if (null != signature && !"".equals(signature)) {
				signature = signature.substring(0, signature.length() - 1);
			}
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(signature.getBytes());
		    for (byte oneB : digest) {
		    	String str = Integer.toHexString(oneB & 0xff);
		    	if (str.length() == 1) {
		             str="0"+str;
		         }
		         buffer.append(str);
		      }
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
		jssdk.setAppId(appId);
		jssdk.setTimestamp(timestamp);
		jssdk.setSignature(url);
		jssdk.setNonceStr(nonceStr);
		jssdk.setSignature(signature);
		return jssdk;
	}
}
